﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Vit.Web.Mvc
{
    public class CriteriaFilterProvider : IFilterProvider
    {
        private readonly List<FilterRegistryItem> items;

        public CriteriaFilterProvider()
        {
            items = new List<FilterRegistryItem>();
        }
        
        #region IFilterProvider Members

        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            List<Filter> filters = new List<Filter>();

            foreach (FilterRegistryItem item in items)
            {
                if (item.Match(controllerContext, actionDescriptor))
                {
                    object filterObject = DependencyResolver.Current.GetServices(item.FilterType);
                    filters.Add(new Filter(filterObject, FilterScope.Action, null));
                }
            }

            return filters;
        }

        #endregion

        public void Clear()
        {
            items.Clear();
        }

        public void Add(IEnumerable<IFilterCriteria> filterCriteria, Type filterType)
        {
            items.Add(new FilterRegistryItem(filterCriteria, filterType));
        }
    }
}
